package com.education.basic.dao.impl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.education.basic.dao.StudentDao;
import com.education.basic.entity.Student;
import com.yunshangwoniu.core.baseDao.impl.BaseDaoImpl;
import com.yunshangwoniu.core.utils.Logger;

@Component("studentDao")
public class StudentDaoImpl extends BaseDaoImpl<Student> implements StudentDao
{

	@Resource
	private SessionFactory sessionFactory;
	
	@Override
	@Transactional
	public Student getByDepartCodeAndMajorCode(String departmentCode, String majorCode)
	{
		Logger.debug(this.getClass(), String.format("excute getByDepartCodeAndMajorCode from student when [departmentCode:%s;professionId:%s]", departmentCode,majorCode));
		Session session = sessionFactory.getCurrentSession();
		String hql = "from Student s where s.departmentId=? and s.professionId=? order by s.createTime desc limit 0,1";
		Query q  = session.createQuery(hql).setFirstResult(0).setMaxResults(1);
		q.setString(0, departmentCode);
		q.setString(1, majorCode);
		Student t2 = (Student)q.uniqueResult();
		if(t2==null)
		{
			Logger.debug(this.getClass(), String.format(" excute getByDepartCodeAndMajorCode not found!! student like [departmentCode:%s;professionId:%s]", departmentCode,majorCode));
			return null;
		}else
		{
			Logger.debug(this.getClass(),String.format("excute getByDepartCodeAndMajorCode sucucss [name:%s;username:%s]", t2.getName(),t2.getUsername()));
			return t2;
		}
	}

	@Override
	@Transactional
	public Student getByStuNO(String stuNo) 
	{
		Session session = sessionFactory.getCurrentSession();
		String hql = "from Student s where s.stuNum=?";
		Query q  = session.createQuery(hql);
		q.setString(0, stuNo);
		try
		{
			Student t2 = (Student)q.uniqueResult();
			Logger.debug(this.getClass(), String.format("get student success by [stuNum:%s]", stuNo));
			return t2;
		}catch(Exception e)
		{
			Logger.debug(this.getClass(), String.format("get student fail by [stuNum:%s]", stuNo));
			return null;
		}
	}

}
